package com.io.nettyflow.serverHandler;

import com.io.config.SpringContextUtil;
import com.io.model.BaseModel;
import com.io.webflow.mapper.RegisterMapper;
import com.io.nettyflow.rounter.GeneralRouter;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * Created by yangyx on 2016/7/21
 *
 * 业务处理就放在这里
 */
@ChannelHandler.Sharable
public class VtChannelHandler extends ChannelInboundHandlerAdapter {

    private GeneralRouter generalRouter=SpringContextUtil.getBean(GeneralRouter.class);

    static private VtChannelHandler _sharedObj = null;

    static public VtChannelHandler sharedObj() {
        if(_sharedObj==null){
            _sharedObj = new VtChannelHandler();
        }
        return _sharedObj;
    }
    /**
     *@Author yangyx 【yang_yaxu@launchdesign.com.cn】
     *@Date  2016/8/1 13:54
     *  串通后执行的第一个方法
     */
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        generalRouter.onClientConnected(ctx);
    }
    /**
     *@Author yangyx 【yang_yaxu@launchdesign.com.cn】
     *@Date  2016/8/1 13:59
     *处理逻辑的方法，我们一般都给业务处理放在这里
     */
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        generalRouter.handlerModel(ctx, (BaseModel) msg);
    }
    /**
     *@Author yangyx 【yang_yaxu@launchdesign.com.cn】
     *@Date  2016/8/1 14:03
     *客户端断开后执行的方法
     */
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        generalRouter.onClientDisconnected(ctx);
    }
    /**
     *@Author yangyx 【yang_yaxu@launchdesign.com.cn】
     *@Date  2016/8/2 19:27
     *执行完channelRead方法后的一个方法
     */
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
    /**
     *@Author yangyx 【yang_yaxu@launchdesign.com.cn】
     *@Date  2016/8/1 14:00
     *当出现异常的时候，会触发这个方法
     */
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        generalRouter.onException(ctx, cause);
    }
    /**
     *@Author yangyx 【yang_yaxu@launchdesign.com.cn】
     *@Date  2016/8/1 14:02
     *心跳超时用到的方法
     */
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
                ctx.close();
            }
        }
    }

}
